import CryptoJS from 'crypto-js';

/**
 * 获取AES加密之后的字符串
 * @param {*} data 需要加密的字符串
 * @param {*} key 秘钥
 * @param {*} iv 偏移向量
 */
export function getAesString(data, key, iv) { // 加密
  key = CryptoJS.enc.Latin1.parse(key);
  iv = CryptoJS.enc.Latin1.parse(iv);
  var srcs = CryptoJS.enc.Utf8.parse(data);

  var encrypted = CryptoJS.AES.encrypt(srcs, key,
    {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  return encrypted;
}

/**
 * 获取解密之后的字符串
 * @param {*} encrypted 需要解密的字符串
 * @param {*} key 秘钥
 * @param {*} iv 偏移向量
 */
export function getDAesString(encrypted, key, iv) { // 解密
  key = CryptoJS.enc.Latin1.parse(key);
  iv = CryptoJS.enc.Latin1.parse(iv);
  var decrypted = CryptoJS.AES.decrypt(encrypted, key,
    {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

/**
 * 针对接口规则的加密方法
 * @param {*} data
 */
export function getHeaderAES(data) {
  const pos = Math.floor(Math.random() * (32 - 0) + 0);
  const key = CryptoJS.MD5('key').toString(CryptoJS.enc.Hex);
  const str = key + key;
  const iv = str.slice(pos, pos + 16);
  const prefix = String.fromCharCode(pos + 48);

  const encrypted = getAesString(data, key, iv);
  const enstr = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  const finalEncrypt = CryptoJS.enc.Utf8.parse(prefix + enstr);
  const finalBase64 = CryptoJS.enc.Base64.stringify(finalEncrypt);
  return finalBase64;
}
